# webhook_listener.py
from flask import Flask, request, abort
import subprocess

app = Flask(__name__)

# --- 配置 ---
WEBHOOK_SECRET = 'my_test_secret_123' # ‼️ 换成你自己的测试密码
DEPLOY_SCRIPT_PATH = './deploy.sh'   # 部署脚本就在当前目录下

@app.route('/webhook', methods=['POST'])
def gitee_webhook():
    gitee_token = request.headers.get('X-Gitee-Token')
    if not gitee_token or gitee_token != WEBHOOK_SECRET:
        abort(401)
    
    event = request.headers.get('X-Gitee-Event')
    print(event)
    if event == 'Push Hook':
        print(f"✅ 收到 Push 事件，准备执行部署脚本...")
        try:
            # 直接执行同目录下的部署脚本
            subprocess.Popen(['/bin/bash', DEPLOY_SCRIPT_PATH])
            return 'Webhook received.', 202
        except Exception as e:
            print(f"❌ 触发部署脚本时出错: {e}")
            return 'Failed to start deployment process.', 500

    return 'Not a push event, ignored.', 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)
